package com.cqs.leetcode.string;

import java.util.Arrays;
import java.util.Stack;

/**
 * @author lixiaowen
 * @create 2020-01-01
 */
public class SimplifyPath71 {

    static class Solution {

        public String simplifyPath(String path) {
            String str = "/";
//            path = path.replaceAll(str + str, str);
            String[] split = path.split(str);
            Stack<String> stack = new Stack<>();
            for (String s : split) {
                if ("..".equals(s) ) {
                    if ( stack.size() > 0){
                        stack.pop();
                    }
                } else if (".".equals(s) || "".equals(s)) {
                    continue;
                } else {
                    stack.push(s);
                }
            }
            String result = "";
            while (!stack.isEmpty()) {
                result = "/" + stack.pop() + result;
            }
            return result.length() > 0 ? result : "/";
        }
    }

    public static void main(String[] args) {
        String[] cases = new String[]{
                "/a/../../b/../c//.//",
                "/a/./b/../../c/",
                "/home//foo/"
        };
        Solution solution = new Solution();
        Arrays.stream(cases).forEach(s -> {
            String s1 = solution.simplifyPath(s);
            System.out.println("source:" + s + "\t result:" + s1);
        });
    }
}
